package reflect;

import reflect.annotations.AutoRunClass;

import java.io.File;

/**
 * 扫描于当前类Test4所在同一个包中的所有类，并实例化那些被@AutoRunClass注解
 * 标注的类
 */
public class Test04 {
    public static void main(String[] args) throws Exception{
        Class cls = Test04.class;
        String packageName = cls.getPackage().getName();
        File dir = new File(cls.getResource(".").toURI());
        File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
        for (File sub :subs){
            String fileName = sub.getName();
            String className = fileName.substring(0,fileName.indexOf("."));
            className = packageName+"."+className;
            Class c = Class.forName(className);
            if(c.isAnnotationPresent(AutoRunClass.class)){
                System.out.println("实例化:"+className);
                Object o = c.newInstance();
                System.out.println(o);
            }
        }
    }
}
